window.onload = () => {

    // 搜索歌曲/歌手/用户
    function ajaxTool(method, url, data, cb) {
        const xhr = new XMLHttpRequest();

        // 真正处理好的请求地址
        let newUrl = url + '/search?keywords=' + data;

        xhr.open(method, newUrl);
        xhr.send();
        xhr.onload = function () {
            if (xhr.status === 200) {
                let res = JSON.parse(xhr.responseText).result.songs;
                cb(res);
                play(method, url);
            }
        }
    }

    // 渲染歌单列表
    function rederDom(data) {
        const con = document.querySelector('.content');

        let str = '';

        str += `
        <table border cellpadding="10px">
            <thead>
                <tr>
                    <th>歌曲</th>
                    <th>歌手</th>
                </tr>
            </thead>
        <tbody>
        `
        data.forEach(item => {
            str += `
                <tr data-id="${item.id}">
                    <td>${item.name}</td>
                    <td>${item.al.name}</td>
                </tr>`
        });
        str += `</tbody></table>`;

        con.innerHTML = str;
    }

    
    const input = document.querySelector('.search');
    input.onkeydown = (e) => {
        if (input.value == '') return;
        if (e.keyCode == 13) {
            ajaxTool("get", 'https://service-0hf83aqu-1307500701.gz.apigw.tencentcs.com/release', input.value, rederDom);
        }
    }

    // 创建播放器
    let audio = document.createElement('audio');
    function play(method, url) {
        const tbody = document.querySelector('table>tbody');
        tbody.onclick = (e) => {
            if (e.target.nodeName == 'TD') {
                // console.log(Number(e.target.parentElement.getAttribute('data-id')));
                const musicId = Number(e.target.parentElement.getAttribute('data-id'));

                // 获取音乐播放 url 并 播放音乐
                const xhr = new XMLHttpRequest();
                let newUrl = url + '/song/url?id=' + musicId;
                xhr.open(method, newUrl);
                xhr.send();
                xhr.onload = function () {
                    if (xhr.status === 200) {
                        let musicUrl = JSON.parse(xhr.responseText).data[0].url;
                        audio.innerHTML = `<source src="${musicUrl}" type="audio/mpeg">`;
                        audio.load();
                        audio.play();
                    }
                }
            }
        }
    }
};